package com.example.test.主方法运行测试;


import cn.hutool.core.collection.CollectionUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

// 大数据量下,利用多线程处理数据
public class 多线程执行 {

    public static void main(String[] args) throws InterruptedException {


        ArrayList<Integer> objects = CollectionUtil.newArrayList();
        for (int i = 1; i <= 100; i++) {
            objects.add(i);
        }

        List<Integer> result = CollectionUtil.newArrayList();
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        CountDownLatch countDownLatch = new CountDownLatch(10);// 计数器
        for (int i = 1; i <= 10; i++) {
            int k = objects.size() / 10;
            List<Integer> integers = objects.subList((i - 1) * k, i * k);
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    int a = 0;
                    for (Integer integer : integers) {
                        a += integer;
                    }
                    System.out.println(a);
                    result.add(a);
                    System.out.println("当前线程name : " + Thread.currentThread().getName() + "==" + new Date());
                    countDownLatch.countDown();// 运行一个线程减少一个
                }
            };
            executorService.execute(runnable);
        }

        countDownLatch.await();  // 主线程阻塞，等计数器==0，唤醒主线程往下执行。
        executorService.shutdown();  // 等内部线程执行完，停止线程

        int finalre = 0;
        for (Integer integer : result) {
            finalre += integer;
        }

        System.out.println(finalre);
    }
}
